package edu.ccut.saturn.basecomponent.database.resultset.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.ccut.saturn.basecomponent.database.resultset.IResultSetSet;
import edu.ccut.saturn.component.SaturnData;

public class ResultSetGetBlob implements IResultSetSet {

	public void setSaturnData(SaturnData saturnData, String key,
			ResultSet resultSet) throws SQLException {

		Blob blob = null;

		if ((blob = resultSet.getBlob(key)) != null) {

			int length = (int) blob.length();

			InputStream inputStream = blob.getBinaryStream();

			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					inputStream);

			byte[] value = new byte[length];

			try {

				bufferedInputStream.read(value);

			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				// if (bufferedInputStream != null){
				// try {
				// bufferedInputStream.close();
				// } catch (IOException e) {
				// e.printStackTrace();
				// }
				// }

				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			saturnData.set(key, value);
		} else {
			saturnData.set(key, blob);
		}
	}
}
